const app = getApp()
const { ModbusRTU } = require('../../utils/modbus')
const { getStringLength } = require('../../utils/stringUtils')
const readNumberOfPoints = 40

Page({
  data: {
    devices: [],
    isScanning: false,
    connectedDevice: null,
    serviceId: '',
    characteristicId: '',
    notifyId:'',
    targetDeviceName: '' // 扫码获取的目标设备名称
  },

  onLoad() {
    this.initBluetooth()
  },

  onShow() {
    // 页面显示时检查连接状态
    this.checkConnectionStatus();
    
    // 设置tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      });
    }
  },

  onHide() {
    // 页面隐藏时停止扫描
    this.stopScan()
  },

  onUnload() {
    this.stopScan();
    wx.offBluetoothDeviceFound();
    if (this.data.connectedDevice) {
      this.disconnectDevice();
    }
    // 页面卸载时确保关闭蓝牙适配器
    if (getApp().globalData.isBluetoothReady) {
      wx.closeBluetoothAdapter({
          complete: () => { console.log('页面卸载，关闭蓝牙适配器。'); }
      });
    }
  },

  initBluetooth() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('蓝牙初始化成功')
        getApp().globalData.isBluetoothReady = true; // 设置全局标志位
        this.getBluetoothAdapterState()
      },
      fail: (res) => {
        getApp().globalData.isBluetoothReady = false;
        wx.showToast({
          title: '请打开蓝牙',
          icon: 'none'
        })
      }
    })
  },

  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        if (res.available) {
          console.log('蓝牙可用')
        } else {
          wx.showToast({
            title: '蓝牙不可用',
            icon: 'none'
          })
        }
      }
    })
  },

  startScan() {
    console.log('请求开始扫描...');
    // 立即更新UI，让用户知道操作已响应
    this.setData({ 
      isScanning: true,
      devices: [] 
    });
    this.resetAndScan();
  },
  
  resetAndScan() {
    console.log('执行蓝牙适配器重置流程...');
    
    // 步骤1：关闭当前蓝牙适配器
    wx.closeBluetoothAdapter({
      complete: (res) => {
        console.log('关闭蓝牙适配器: complete', res.errMsg);
        // 步骤2：短暂延时后，重新打开适配器
        setTimeout(() => {
          wx.openBluetoothAdapter({
            success: (res) => {
              console.log('重新打开蓝牙适配器成功');
              getApp().globalData.isBluetoothReady = true;
              // 步骤3：执行真正的扫描操作
              this.performActualScan();
            },
            fail: (err) => {
              console.error('重新打开蓝牙适配器失败:', err);
              getApp().globalData.isBluetoothReady = false;
              this.setData({ isScanning: false });
              wx.showToast({ title: '无法启动蓝牙，请重试', icon: 'none' });
            }
          });
        }, 200); // 延时200毫秒，给系统反应时间
      }
    });
  },

  performActualScan() {
    console.log('执行核心扫描操作');
    
    // 重新设置监听器
    this.onBluetoothDeviceFound();

    // 开始扫描设备
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery 成功');
      },
      fail: (err) => {
        console.error('startBluetoothDevicesDiscovery 失败:', err);
        this.setData({ isScanning: false });
        wx.showToast({ title: '扫描开启失败', icon: 'none' });
      }
    });

    // 设置10秒后自动停止的定时器
    this.scanTimer = setTimeout(() => {
      console.log('扫描超时，自动停止。');
      this.stopScan();
    }, 10000);
  },

  stopScan() {
    // 清除定时器
    if (this.scanTimer) {
      clearTimeout(this.scanTimer);
      this.scanTimer = null;
    }
    // 仅在扫描状态下才停止
    if (this.data.isScanning) {
      console.log('正在执行停止扫描...');
      wx.stopBluetoothDevicesDiscovery({
        complete: () => {
          console.log('停止扫描操作完成。');
          this.setData({ isScanning: false });
        }
      });
    }
  },
  
  onBluetoothDeviceFound() {
    // 先移除之前的监听器，防止重复监听
    wx.offBluetoothDeviceFound();
    
    wx.onBluetoothDeviceFound((res) => {
      const devices = res.devices
      const newDevices = devices.filter(device => {
        //判断是否device.name只包含数字字符
        
        //计算 device.name字符串长度
        let namelength = getStringLength(device.name)
        
        // 添加调试信息
        console.log('发现设备:', device.name, '类型:', typeof device.name, '长度:', namelength)
        
        return (device.name === 'Ai-Thinker' || device.name === '0' || (/^\d+$/.test(device.name) && namelength === 10)) && 
          !this.data.devices.some(d => d.deviceId === device.deviceId)
      })

      if (newDevices.length > 0) {
        console.log('添加新设备:', newDevices.length, '个')
        this.setData({
          devices: [...this.data.devices, ...newDevices]
        })
      }
    })
  },
  
  connectDevice(e) {
    const device = e.currentTarget.dataset.device
    app.globalData.connectedDevice = device;
    wx.switchTab({
      url: '/pages/device/device',
    })
  },

  checkConnectionStatus() {
    // 检查全局连接状态
    if (app.globalData.connectedDevice) {
      this.setData({
        connectedDevice: app.globalData.connectedDevice
      })
    } else {
      this.setData({
        connectedDevice: null
      })
    }
  },

  disconnectDevice() {
    if (this.data.connectedDevice) {
      wx.closeBLEConnection({
        deviceId: this.data.connectedDevice.deviceId,
        success: (res) => {
          console.log('断开连接成功:', res)
          this.cleanupConnection()
        },
        fail: (res) => {
          console.error('断开连接命令失败:', res)
          // 即使断开连接命令失败，也要清理连接资源
          this.cleanupConnection()
        }
      })
    }
  },

  // 清理连接资源的统一方法
  cleanupConnection() {
    this.setData({ connectedDevice: null })
    app.globalData.connectedDevice = null
    app.globalData.serviceId = ''
    app.globalData.characteristicId = ''
    app.globalData.notifyId = ''
    app.globalData.isConnected = false
    
    // 移除蓝牙特征值变化监听
    wx.offBLECharacteristicValueChange()
    
    console.log('连接资源已清理')
  },

  // 扫码搜索设备
  scanQRCode() {
    wx.scanCode({
      success: (res) => {
        console.log('扫码结果:', res.result)
        const deviceName = res.result.trim()
        
        if (!deviceName) {
          wx.showToast({
            title: '扫码内容为空',
            icon: 'none'
          })
          return
        }
        
        // 验证设备名称是否符合规范
        if (!this.isValidDeviceName(deviceName)) {
          wx.showToast({
            title: '设备名称格式无效',
            icon: 'none',
            duration: 3000
          })
          return
        }
        
        this.setData({
          targetDeviceName: deviceName
        })
        
        wx.showToast({
          title: `开始搜索设备: ${deviceName}`,
          icon: 'none',
          duration: 2000
        })
        
        // 开始搜索指定设备
        this.searchTargetDevice(deviceName)
      },
      fail: (err) => {
        console.error('扫码失败:', err)
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        })
      }
    })
  },

  // 验证设备名称是否符合规范
  isValidDeviceName(deviceName) {
    if (!deviceName || typeof deviceName !== 'string') {
      return false
    }
    
    // 计算设备名称长度
    const nameLength = getStringLength(deviceName)
    
    // 验证规则：
    // 1. 特定设备名: 'Ai-Thinker'
    // 2. 特殊设备名: '0'
    // 3. 10位纯数字字符串
    const isValid = (
      deviceName === 'Ai-Thinker' || 
      deviceName === '0' || 
      (/^\d+$/.test(deviceName) && nameLength === 10)
    )
    
    console.log('设备名称验证:', {
      deviceName,
      nameLength,
      isValid,
      isAiThinker: deviceName === 'Ai-Thinker',
      isZero: deviceName === '0',
      isTenDigits: /^\d+$/.test(deviceName) && nameLength === 10
    })
    
    return isValid
  },

  // 搜索指定设备
  searchTargetDevice(targetName) {
    console.log('开始搜索目标设备:', targetName)
    
    // 清空之前的设备列表
    this.setData({ 
      devices: [],
      isScanning: true 
    })
    
    // 设置设备发现监听器
    this.onBluetoothDeviceFoundForTarget(targetName)
    
    // 开始扫描
    this.resetAndScanForTarget(targetName)
  },

  // 为目标设备搜索设置监听器
  onBluetoothDeviceFoundForTarget(targetName) {
    // 先移除之前的监听器
    wx.offBluetoothDeviceFound()
    
    wx.onBluetoothDeviceFound((res) => {
      const devices = res.devices
      const targetDevice = devices.find(device => {
        return device.name === targetName
      })
      
      if (targetDevice) {
        console.log('找到目标设备:', targetDevice)
        this.setData({
          devices: [targetDevice],
          isScanning: false
        })
        
        // 停止扫描
        this.stopScan()
        
        // 自动连接设备
        this.autoConnectDevice(targetDevice)
      }
    })
  },

  // 自动连接设备
  autoConnectDevice(device) {
    wx.showLoading({
      title: '正在连接...'
    })
    
    // 延迟一下再连接，确保扫描完全停止
    setTimeout(() => {
      app.globalData.connectedDevice = device
      wx.hideLoading()
      
      wx.showToast({
        title: '连接成功',
        icon: 'success',
        duration: 1500
      })
      
      // 跳转到设备页面
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/device/device'
        })
      }, 1500)
    }, 500)
  },

  // 为目标设备搜索重置蓝牙适配器
  resetAndScanForTarget(targetName) {
    console.log('为目标设备搜索重置蓝牙适配器...')
    
    wx.closeBluetoothAdapter({
      complete: (res) => {
        console.log('关闭蓝牙适配器: complete', res.errMsg)
        setTimeout(() => {
          wx.openBluetoothAdapter({
            success: (res) => {
              console.log('重新打开蓝牙适配器成功')
              getApp().globalData.isBluetoothReady = true
              this.performActualScanForTarget(targetName)
            },
            fail: (err) => {
              console.error('重新打开蓝牙适配器失败:', err)
              getApp().globalData.isBluetoothReady = false
              this.setData({ isScanning: false })
              wx.showToast({ 
                title: '无法启动蓝牙，请重试', 
                icon: 'none' 
              })
            }
          })
        }, 200)
      }
    })
  },

  // 为目标设备执行扫描
  performActualScanForTarget(targetName) {
    console.log('为目标设备执行扫描:', targetName)
    
    // 重新设置监听器
    this.onBluetoothDeviceFoundForTarget(targetName)

    // 开始扫描设备
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery 成功')
      },
      fail: (err) => {
        console.error('startBluetoothDevicesDiscovery 失败:', err)
        this.setData({ isScanning: false })
        wx.showToast({ title: '扫描开启失败', icon: 'none' })
      }
    })

    // 设置15秒后自动停止的定时器
    this.scanTimer = setTimeout(() => {
      console.log('目标设备搜索超时，自动停止。')
      this.stopScan()
      
      if (this.data.devices.length === 0) {
        wx.showToast({
          title: `未找到设备: ${targetName}`,
          icon: 'none',
          duration: 3000
        })
      }
    }, 15000)
  }
}) 